import Vue from "vue"
const state = {
	cartList:[],//分类中的购物车列表
	activityCartList:{}//带活动的购物车列表
}
 const getters = {
	 //检查商品是否存在(仓库)购物车中
	 checkProductExists(state){
		 //计算属性
		 return function(skuId){
			 const pos = state.cartList.findIndex(item=>item.skuId===skuId)
			 return pos === -1?false:true
		 }
	 },
	 //返回当前商品数量
	 getProductSkuNum(state){
		 return function(skuId){
			 let index = state.cartList.findIndex(item=>item.skuId===skuId)
			 return index!==-1?state.cartList[index].skuNum:0
		 }
	 },
	 //获取购物车商品信息列表
	 getCartInfoList(state){
		 return state.activityCartList.carInfoVoList
	 }
 }
const mutations = {
	// 添加到购物车
	addCartMutation(state,payload){
		state.cartList.push(payload)
	},
	// 获取不带活动的商品列表
	getCartListMutaiton(state,payload){
		state.cartList = payload
	},
	//修改购物车商品数量
	changeSkuNumMutation(state,payload){
		const {skuId,value,currentBuyNum}  = payload
		const index = state.cartList.findIndex(item=>item.skuId===skuId)
		if(currentBuyNum<1){
			//当当前数量<1 将该商品从购物车移除
			
			state.cartList.splice(index,1)
		}else{
			//否则购物车的该商品数量进行更新
			state.cartList[index].skuNum+=value
		}
		
	},
	//删除购物车
	deleteCartMutation(state,skuId){
		const index = state.cartList.findIndex(item=>item.skuId===skuId)
		state.cartList.splice(index,1)
	},
	// 获取活动的购物车列表
	getActivityCartListMutation(state,payload){
		state.activityCartList = payload
	}
}
const actions = {
	// 添加到购物车
	async addCartAction({commit},payload){
		//给对象添加响应式属性 这些属性原来的对象没有 只有购物车属性的对象才有 请求需要
		Vue.set(payload,"skuNum",1)
		Vue.set(payload, "skuId", payload.id)
		Vue.set(payload, "isChecked", 1)
		//发送请求 数据库响应该需求
		await this._vm.$u.api.getAddToCart({
			skuId:payload.skuId,
			skuNum:payload.skuNum
		})
		// 修改本地数据 保持和数据库同步
		commit("addCartMutation",payload)
	},
	// 获取不带活动的商品列表
	async getCartListAction({commit}){
		let res = await this._vm.$u.api.getCartList()
		commit("getCartListMutaiton",res)
	},
	//修改购物车商品数量
	async changeSkuNumAction({commit,dispatch},payload){
		const {skuId,value,currentBuyNum} = payload
		if(currentBuyNum<1){
			dispatch("deleteCartAction",skuId)
		}else{
			await this._vm.$u.api.getAddToCart({
				skuId:skuId,
				skuNum:value
			})
		}
		commit("changeSkuNumMutation",payload)
	},
	//删除购物车指定商品
	async deleteCartAction({commit},skuId){
		//删除购物车的数据
		await this._vm.$u.api.deleteCart(skuId)
		
		await commit("deleteCartMutation",skuId)
	},
	//获取带有活动的购物车商品列表
	async getActivityCartListAction({commit},payload){
		let showLoading = false
		if(payload) showLoading = true
		let res = await this._vm.$u.api.getActivityCartList({
			showLoading,
		})
		commit('getActivityCartListMutation',res)
	}
}
export default {
	namespaced:true,
	state,
	getters,
	mutations,
	actions
 }